<template>
  <div class="">
    <div>手写简单双向数据绑定</div>
    <input type="text" id="myInput" />
    <p>你好，<span id="greetingSpan"></span></p>
  </div>
</template>

<script setup lang="ts">
  import { nextTick } from 'vue'

  const data = {
    message: 'Hello'
  }
  nextTick(() => {
    // 获取输入框和显示元素
    const myInput = document.getElementById('myInput')
    const greetingSpan = document.getElementById('greetingSpan')
    // function bindInputToModel(obj, key) {
    //   console.log(obj, key, '111')
    //   myInput.addEventListener('input', (event: any) => {
    //     obj[key] = event.target.value
    //     console.log(obj[key], 'message')
    //   })
    // }
    // bindInputToModel(data, 'meaasge')
    function bindInputToModel(inputElement, obj, key) {
      inputElement.addEventListener('input', () => {
        obj[key] = inputElement.value
      })
    }
    const input = document.getElementById('myInput')
    bindInputToModel(input, data, 'message')

    function defineReactive(obj, key, value) {
      let currentVal = value
      //   console.log(obj, 'obj')
      //   console.log(key, 'key')
      //   console.log(value, 'value')
      Object.defineProperty(obj, key, {
        get() {
          console.log(currentVal, 'get获取数据')
          return currentVal
        },
        set(newVal) {
          if (newVal == currentVal) return
          currentVal = newVal
          greetingSpan.innerHTML = newVal
          notify(key, newVal)
        }
      })
    }

    function notify(key: any, value: any) {
      console.log(`Property ${key} chaned to ${value}`)
    }

    function observe(obj: object) {
      Object.keys(obj).forEach(key => {
        defineReactive(obj, key, obj[key])
      })
    }
    observe(data)
  })
</script>

<style lang="less" scoped></style>
